<template>
  <div class="comment-list">
    <el-button @click="$router.go(-1)" icon="el-icon-arrow-left" type="text">返回</el-button>
    <h2>评论列表</h2>
    <el-card class="topic-card">
      <span>用户：{{ selectedTopic.realName }}在问</span>
      <h3>{{ selectedTopic.title }}</h3>
      <p>"{{ selectedTopic.content }}"</p>
    </el-card>
    <el-card v-for="comment in comments" :key="comment.id" class="comment-card">
      <div>{{ comment.content }}</div>
      <div class="comment-info">
        <span>{{ comment.realName }}</span>
        <span>{{ comment.createdTime }}</span>
      </div>
      <el-collapse>
        <el-collapse-item title="查看回复" v-if="comment.replies && comment.replies.length > 0">
          <el-card v-for="reply in comment.replies" :key="reply.id" class="reply-card">
            <div>{{ reply.content }}</div>
            <div class="reply-info">
              <span>{{ reply.realName }}-</span>
              <span>{{ reply.createdTime }}</span>
            </div>
          </el-card>
        </el-collapse-item>
      </el-collapse>
      <el-button @click="toggleReplyForm(comment.id)" type="text">回复</el-button>
      <el-form v-if="replyForms[comment.id] && replyForms[comment.id].visible" :model="replyForms[comment.id]" :rules="rules" ref="newReplyForm" class="reply-form">
        <el-form-item prop="content">
          <el-input v-model="replyForms[comment.id].content" placeholder="请输入回复内容"></el-input>
        </el-form-item>
        <el-button type="primary" @click="addReply(comment.id)">回复</el-button>
      </el-form>
    </el-card>
    <el-form :model="newComment" :rules="rules" ref="newCommentForm" class="new-comment-form">
      <el-form-item prop="content">
        <el-input v-model="newComment.content" placeholder="添加新的评论"></el-input>
      </el-form-item>
      <el-button type="primary" @click="addComment">添加评论</el-button>
    </el-form>
    <el-button @click="$router.go(-1)" style="margin-top: 10px;">返回</el-button>
    <div style="height: 14.2vw"></div>

    <Footer />
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { ElCard, ElButton, ElForm, ElFormItem, ElInput, ElCollapse, ElCollapseItem } from 'element-plus';
import Footer from '@/components/Footer.vue';
import axios from "../plugin/axiosInstance";

export default {
  components: {
    ElCard,
    ElButton,
    ElForm,
    ElFormItem,
    ElInput,
    ElCollapse,
    ElCollapseItem,
    Footer,
  },
  setup() {
    const route = useRoute();
    const topicId = ref(route.query.topicId);

    const selectedTopic = ref({});
    const comments = ref([]);
    const newComment = ref({
      content: '',
    });

    const rules = {
      content: [{ required: true, message: '请输入回复内容', trigger: 'blur' }],
    };

    const replyForms = reactive({});

    const getTopic = async () => {
      try {
        const response = await axios.get(`/reply/getTopicById/${topicId.value}`);
        selectedTopic.value = response.data.data;
      } catch (error) {
        console.error('获取主题失败:', error);
      }
    };

    const fetchComments = async () => {
      try {
        const response = await axios.get(`/reply/getTopicReplies/${topicId.value}`);
        comments.value = response.data.data;

        // Initialize reply forms for each comment
        comments.value.forEach(comment => {
          if (!replyForms[comment.id]) {
            replyForms[comment.id] = { content: '', visible: false };
          }
        });
      } catch (error) {
        console.error('获取评论失败:', error);
      }
    };

    const toggleReplyForm = (commentId) => {
      // Hide all reply forms
      Object.keys(replyForms).forEach(id => {
        replyForms[id].visible = false;
      });
      // Show the current reply form
      replyForms[commentId].visible = !replyForms[commentId].visible;
    };

    const addReply = async (commentId) => {
      try {
        const response = await axios.post(`/reply/addReply`, {
          content: replyForms[commentId].content,
          topicId: topicId.value,
          parentId: commentId, // 回复的一级评论
        });
        console.log('添加回复成功:', response.data);
        fetchComments(); // 重新获取评论列表
        replyForms[commentId].content = ''; // 清空回复框
        replyForms[commentId].visible = false; // 隐藏回复框
      } catch (error) {
        console.error('添加回复失败:', error);
      }
    };

    const addComment = async () => {
      try {
        console.log(newComment.value.content);
        const response = await axios.post(`/reply/addReply`, {
          content: newComment.value.content,
          topicId: topicId.value,
          parentId: 0, // 0 表示这是一个一级评论
        });
        console.log('添加评论成功:', response.data);
        await fetchComments(); // 重新获取评论列表
        newComment.content = ''; // 清空评论框
      } catch (error) {
        console.error('添加评论失败:', error);
      }
    };

    onMounted(() => {
      getTopic();
      fetchComments();
    });

    return {
      selectedTopic,
      comments,
      newComment,
      replyForms,
      rules,
      toggleReplyForm,
      addReply,
      addComment,
    };
  },
};
</script>

<style scoped>
.comment-list {
  padding: 10px;
}

.topic-card {
  margin-bottom: 10px;
}

.comment-card {
  margin-bottom: 10px;
}

.reply-card {
  margin-top: 10px;
  margin-left: 20px;
  background-color: #f9f9f9;
}

.comment-info, .reply-info {
  font-size: 12px;
  color: #666;
}

.reply-form, .new-comment-form {
  margin-top: 10px;
}
</style>
